exports.install = function(framework) {

    framework.route('/browse/', view_browse);
	framework.route('/categories/{categoryId}/', view_category);
    
};

// View all products from database
function view_browse() {    
    var self = this;
//	var logger=self.module('services').getService('logger');
//	logger.log('Hello!');
	var url= framework.global.ishUrl + framework.global.site + '/-/categories/Cameras-Camcorders/575/products';
	var data;
		var callback = function(err, data, statusCode, headers) {
		obj = JSON.parse(data);
		 var model = {
            products: obj.elements,
        };
		for (var i = 0; i < model.products.length; i++) 
		{ 
			var data = getCachedProductData(model.products[i].uri);
			framework.global.products.push({ name: model.products[i].name, title: model.products[i].title,uri: ''});
		}
		self.view('list', framework.global.products);
	}
	if(framework.global.products.length == 0)
	{
		utils.request(url,'GET',data,callback);  
	}
	else
	{
		self.view('list', framework.global.products);
	}
	
};

// View all category from database
function view_category(categoryId) {    
    var self = this;
	//we can modify global category any where in controller...
	//framework.global.category.push({ name: 'Home', link: '/browse/' });
	//framework.global.ishUrl = http://hp-pc:83/INTERSHOP/rest/WFS/PrimeTech-PrimeTechSpecials-Site
	var url = framework.global.ishUrl + framework.global.site + '/-' + self.req.uri.path ;
	var data;

	 var callback = function(err, data, statusCode, headers) {
       obj = JSON.parse(data);
		 var model = {
            categories: obj.subCategories.elements,
			name: obj.name,
        };
		
		self.view('categorylist', model);
	}	
	utils.request(url,'GET',data,callback); 
};

function getCachedProductData(uri)
{
    var key = uri.substring(uri.lastIndexOf("/")+1);
	var data;
	var callback = function(err, data, statusCode, headers) 
	{
			obj = JSON.parse(data);
			framework.global.cache[uri] = obj;
	}	
	//check in cache
	if(framework.global.cache[key] === undefined)
	{
		console.log("not in cache");
		var productUrl = framework.global.ishUrl  + uri;
		utils.request(productUrl,'GET',data,callback); 
	}
}



